/******************************************************************************
 *
 *       Filename:  test.cpp
 *
 *    Description:  test
 *
 *        Version:  1.0
 *        Created:  2020年11月10日 22时00分07秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  yangkun (yk)
 *          Email:  xyyangkun@163.com
 *        Company:  yangkun.com
 *
 *****************************************************************************/

#include <signal.h>
#include "Util/util.h"
#include "Util/logger.h"
#include <iostream>
#include "Rtsp/UDPServer.h"
#include "Rtsp/RtspPlayerImp.h"
#include "Player/MediaPlayer.h"
#include "Util/onceToken.h"
#include "FFMpegDecoder.h"
#include "YuvDisplayer.h"
#include "Extension/H265.h"

using namespace std;
using namespace toolkit;
using namespace mediakit;


/**
 * 合并一些时间戳相同的frame
 */
class FrameMerger {
public:
    FrameMerger() = default;
    virtual ~FrameMerger() = default;

    void inputFrame(const Frame::Ptr &frame,const function<void(uint32_t dts,uint32_t pts,const Buffer::Ptr &buffer)> &cb){
        if (!_frameCached.empty() && _frameCached.back()->dts() != frame->dts()) {
            Frame::Ptr back = _frameCached.back();
            Buffer::Ptr merged_frame = back;
            if(_frameCached.size() != 1){
                string merged;
                _frameCached.for_each([&](const Frame::Ptr &frame){
                    if(frame->prefixSize()){
                        merged.append(frame->data(),frame->size());
                    } else{
                        merged.append("\x00\x00\x00\x01",4);
                        merged.append(frame->data(),frame->size());
                    }
                });
                merged_frame = std::make_shared<BufferString>(std::move(merged));
            }
            cb(back->dts(),back->pts(),merged_frame);
            _frameCached.clear();
        }
        _frameCached.emplace_back(Frame::getCacheAbleFrame(frame));
    }
private:
    List<Frame::Ptr> _frameCached;
};

#include <unistd.h>
int main(int argc, char *argv[]) 
{
    static char *url = argv[1];

     //设置日志
    Logger::Instance().add(std::make_shared<ConsoleChannel>());
    Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>());

    if (argc != 3) {
        ErrorL << "\r\n测试方法：./test_player rtxp_url rtp_type\r\n"
               << "例如：./test_player rtsp://admin:123456@127.0.0.1/live/0 0\r\n"
               << endl;
        return 0;
	}
#if 1 
    MediaPlayer::Ptr player(new MediaPlayer());
    weak_ptr<MediaPlayer> weakPlayer = player;
    player->setOnPlayResult([weakPlayer](const SockException &ex) {
#else
    RtspPlayerImp::Ptr player(new RtspPlayerImp());
    weak_ptr<RtspPlayerImp> weakPlayer = player;
    player->setOnPlayResult([weakPlayer](const SockException &ex) {
#endif
        InfoL << "OnPlayResult:" << ex.what();
        auto strongPlayer = weakPlayer.lock();
        if (ex || !strongPlayer) {
            return;
        }

        auto viedoTrack = strongPlayer->getTrack(TrackVideo);
        if (!viedoTrack) {
            WarnL << "没有视频!";
            return;
        }

        AnyStorage::Ptr storage(new AnyStorage);

        viedoTrack->addDelegate(std::make_shared<FrameWriterInterfaceHelper>([storage](const Frame::Ptr &frame_in) {
 
            auto frame = Frame::getCacheAbleFrame(frame_in);
			auto &merger = (*storage)["merger"];
			if(!merger){
			merger.set<FrameMerger>();
			}

			merger.get<FrameMerger>().inputFrame(frame,[&](uint32_t dts,uint32_t pts,const Buffer::Ptr &buffer){
					printf("bufsize:%d\n", buffer->size());
			});
		}));
	});

    player->setOnShutdown([](const SockException &ex) {
        ErrorL << "OnShutdown:" << ex.what();
    });

	InfoL << "type:" << argv[2];

    (*player)[kRtpType] = atoi(argv[2]);
    player->play(argv[1]);

	sleep(10);
	return 0;
}

